<template>
    <div class="bg-container">
        <div class="my-header">
            <div class="search-form" v-if="headerShow">
                <a-form size="mini" :model="pageData" layout="inline">
                    <a-form-item label="物料规格">
                        <a-select popup-container="html"  :style="{ width: '320px' }" :loading="loading"
                            @search="handleSearch" v-model="pageData.dropDownData" :filter-option="false" allow-search
                            allow-clear @focus="focusSel">
                            <a-option v-for="item in pageData.nameList as any" :value="item.specName">{{ item.specName
                            }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                </a-form>
            </div>
              <div class="my-divisders">
            <a-divider orientation="center">
                <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
            </a-divider>
             </div>
            <div class="my-tool-bar">
                <!-- '导出', '导入' -->
                <Toolbar :items="pageData.btnList" @add="addHandler" @del="deleteHandler" @select="selectHandler"
                    @export="exports" @import="importHandler" @excel="downloadHandler">
                </Toolbar>
            </div>
        </div>
    </div>
    <a-table 
    size="mini"
    :scrollbar="true" sticky-header :style="{ height: pageData.rHeight + 'px' }"
        @page-change="pagination.change" stripe :bordered="true" :columns="tableColumns"
        :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }" v-model:selected-keys="selectedRowKeys"
        :loading="table.tableLoading" :data="table.dataList"
        :pagination="{ size: 'mini', current: pagination.page, pageSize: pagination.pageSize, total: pagination.total }"
        :rowKey="rowKey">
        <template #action="{ record }">
            <a-button type="primary" size="mini" status="warning" @click="editHandler(record)" v-if="pageData.isEdit">
                <template #icon>
                    <icon-edit />
                </template>
                修 改
            </a-button>
        </template>
    </a-table>

    <a-drawer ok-text='保存' cancel-text='关闭' :drawer-style="{ 'zIndex': 9999 }" :width="400" :visible="pageData.showAdd"
        :mask-closable="false" unmountOnClose @ok="sideOk" @cancel="pageData.showAdd = false" :ok-loading="pageData.pageLoading">
        <template #title>
            {{ pageData.sideTitle }}
        </template>
        <div>
            <a-form ref="formRef" layout="vertical" :model="dataForm">
                <a-form-item label="物料大类">
                    <a-select popup-container="html"  :style="{ width: '320px' }" :loading="loadings"
                        @search="handleSearchs" v-model="dataForm.bigClassName" :filter-option="false" allow-search
                        allow-clear @focus="focusSels" @change="focusSelsss">
                        <a-option v-for="item in pageData.nameLists as any" :value="item.bigClassName">{{
                                item.bigClassName
                        }}</a-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="物料小类">
                    <a-select popup-container="html"  v-model="dataForm.subClassName" :style="{ width: '320px' }" >
                        <a-option v-for="item in dataListXl">{{ item.subClassName }}</a-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="编号" field="specCode"
                    :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]"
                    :validate-trigger="['change', 'blur']">
                    <a-input placeholder="" v-model="dataForm.specCode" @blur="inputBlur" />
                </a-form-item>
                <a-form-item label="物料规格" field="specName" :rules="[{ required: true, message: '物料规格必填' }]"
                    :validate-trigger="['change', 'blur']">
                    <a-input placeholder="" v-model="dataForm.specName" />
                </a-form-item>
                <a-form-item label="备注" field="remark">
                    <a-input  v-model="dataForm.remark" />
                </a-form-item>
            </a-form>
        </div>
    </a-drawer>
</template>

<script setup lang="ts">
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table';
import emitter from "@/hooks/useEventBus";
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue';
import { Form, Message, Modal } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { String } from 'lodash';
import { baseURL } from '@/api/axios.config'
import axios from "axios";
import usePermission from '@/store/modules/permission'
import { simplifyMessages } from '@/api/messageSimplification'
interface ProcurementType {
    "id": any
    "bigClassName": any
    "subClassName": any
    "specName": any
    "specCode": any
    "remark":any
}

function doRefresh() {
    pageData.pageLoading = true
    post({
        url: "purchase/MaterialSpec/getPage",
        data: {
            page: pagination.page,
            size: pagination.pageSize,
            deleteState: 0,
            specName: pageData.dropDownData
        },
    })
        .then(({ data, code }: any) => {
            if (code === 200) {
                // table.handleSuccess(data.list);
                table.handleSuccess(data.list);
                pagination.setTotalSize(data.total);
                console.log(table.dataList);
            }
        })
        .catch(console.log).finally(() => {
            pageData.pageLoading = false
        })
}
const { selectedRowKeys, onSelectionChange } = useRowSelection();
const pagination = usePagination(doRefresh);
const table = useTable();
const rowKey = useRowKey("id");
const tableColumns = useTableColumn([

    {
        title: "编号",
        key: "specCode",
        dataIndex: "specCode",
        width: 150
    },
    {
        title: "物料大类",
        key: "bigClassName",
        dataIndex: "bigClassName",
        width: 150
    },
    {
        title: "物料小类",
        key: "subClassName",
        dataIndex: "subClassName",
        width: 150
    },
    {
        title: "物料规格",
        key: "specName",
        dataIndex: "specName",
        width: 150
    },
    {
        title: "创建人",
        key: "createName",
        dataIndex: "createName",
        width: 150
    },
    {
        title: "创建时间",
        key: "createTime",
        dataIndex: "createTime",
        width: 150
    },
    {
        title: "最后修改人",
        key: "updateName",
        dataIndex: "updateName",
        width: 150
    },
    {
        title: "最后修改时间",
        key: "updateTime",
        dataIndex: "updateTime",
        width: 150
    },
    {
        title: "备注",
        key: "remark",
        dataIndex: "remark",
        width: 150
    },
    {
        title: '操作',
        key: 'id',
        slotName: 'action',
        width: 150, fixed: 'right'
    }
]);
const pageData = reactive<{
    nameList: [],
    nameLists: [],
    nameLists1: [],
    showAdd: boolean,
    sideTitle: string,
    dropDownData: any,
    pageLoading: boolean,
    rHeight: any
    btnList: any[],
    isEdit: boolean
}>({
    nameList: [],
    nameLists: [],
    nameLists1: [],
    showAdd: false,
    sideTitle: '新增物料规格',
    dropDownData: "",
    pageLoading: false,
    rHeight: "",
    btnList: [],
    isEdit: false
});
//下拉框得到焦点
const focusSel = () => {
    selCxAll({ specName: '' })
}
//下拉数据 
const options = ref<any>(pageData.nameList);
const loading = ref(false);
const handleSearch = (value: any) => {
    if (value) {
        const ob = { specName: value }
        loading.value = true;
        window.setTimeout(() => {
            selCxAll(ob);
            options.value = pageData.nameList;
            loading.value = false;
        }, 200)
    } else {
        options.value = []
    }
};
//下拉框查询
function selCxAll(val: any) {
    post({
        url: "purchase/MaterialSpec/getFieldValue",
        data: val
    }).then(({ data, code }: any) => {
        if (code === 200) {
            console.log(data);
            // (data as string[]).splice(0, 0, "全部");
            pageData.nameList = data;

        } else {
            Message.error({
                content: "查询失败！",
                duration: 5000,
            });
        }
    });
}

onMounted(() => {
    emitter.on("refresh-ProdductInfo", () => {
        // doRefresh();
        selCxAll({});

    });
    pageData.rHeight = document.getElementsByClassName("main-section")[0]?.clientHeight
    //表格的高
    if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight - 200;

        console.log(pageData.rHeight);

    }
    window.addEventListener('resize', () => {
        pageData.rHeight = document.getElementById("BaseInfoSetting")?.clientHeight

        //表格的高
        if (pageData.rHeight !== undefined) {
            pageData.rHeight = pageData.rHeight - 200;
        }

    })
});
//查询
const selectHandler = () => {
    doRefresh();
}
const queryData = reactive({

    clothType: ""
});
const addHandler = () => {
    //清空数据
    for (const key in dataForm) {
        if (key == "id") {
            dataForm.id = null;
        } else {
            dataForm[key] = '';
        }
    }
    pageData.showAdd = true
    pageData.sideTitle = '新增物料规格'

}

const dataForm = reactive<ProcurementType>({
    "id": null,
    "bigClassName": "",
    "subClassName": "",
    "specName": "",
    "specCode": "",
    "remark":""
})
const formRef = ref<FormInstance>()
const sideOk = () => {
    formRef.value?.validate().then((err) => {
        if (!err) {
            if (pageData.sideTitle === "新增物料规格") {
                dataForm.id = null
                pageData.pageLoading = true
                post({
                    url: "purchase/MaterialSpec/insert",
                    data: [dataForm],
                }).then((res: any) => {
                    if (res.code === 200) {
                        formRef.value?.resetFields();
                        pageData.showAdd = false;
                        doRefresh();
                        Message.success({
                            content: "新增成功",
                            duration: 5000,
                        });
                    } else {
                        Message.error({
                            content: res.message,
                            duration: 5000,
                        });
                    }
                }).then(()=>{
                    pageData.pageLoading = false
                })
            } else {
                post({
                    url: "purchase/MaterialSpec/update",
                    data: [dataForm],
                }).then((res: any) => {
                    if (res.code === 200) {
                        formRef.value?.resetFields();
                        pageData.showAdd = false;
                        doRefresh();
                        //清空数据
                        for (const key in dataForm) {
                            if (key == "id") {
                                dataForm.id = null;
                            } else {
                                dataForm[key] = '';
                            }
                        }
                        Message.success({
                            content: "修改成功",
                            duration: 5000,
                        });
                    } else {
                        Message.error({
                            content:simplifyMessages(res.message),
                            duration: 5000,
                        });
                    }
                });
            }
        }
    });
}
const deleteHandler = () => {
    if (selectedRowKeys.value.length === 0) {
        return
    }
    Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
            post({
                url: 'purchase/MaterialSpec/delete',
                data: selectedRowKeys.value
            }).then(({ code, data ,message}: any) => {
                if (code === 200) {
                    Message.success({
                        content: '删除成功',
                        duration: 5000
                    })
                    pagination.page = 1
                    doRefresh()
                } else {
                    Message.success({
                        content: simplifyMessages(message),
                        duration: 5000
                    })
                }
            })
        }
    })
}
const editHandler = (record: ProcurementType) => {
    dataForm.id = Number(record.id);
    dataForm.specCode = record.specCode
    dataForm.specName = record.specName
    dataForm.bigClassName = record.bigClassName;
    dataForm.subClassName = record.subClassName;
    dataForm.remark = record.remark;
    pageData.sideTitle = '修改物料规格'
    pageData.showAdd = true
};
//判断是否填写了中文
const isChiese = (value: string, cb: Function) => {
    return new Promise<void>(resolve => {
        if (window.encodeURI(value).indexOf('%') !== -1) {
            cb('填写的值不能包含中文！')
        }
        resolve()
    })

}
//input离开焦点 将小写转大写
const inputBlur = () => {
    dataForm.specCode = dataForm.specCode.toUpperCase();
}
//导出
const exports = () => {
    if (selectedRowKeys.value.length === 0) {
        Message.error('请先勾选')
        return
    } else {
        //将表头拼接出来
        let head = "<th>类型编号</th><th>类型名称</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>"
        //拿到当前表格数据与勾选的行做筛选

        let nowRow = table.dataList.filter(function (o) {
            return selectedRowKeys.value.indexOf(o["id"]) !== -1;
        })
        let body = "";
        nowRow.forEach(function (o) {
            body += "<tr><td>" + o["productTypeCode"] + "</td>";
            body += "<td>" + o["productTypeName"] + "</td>";
            body += "<td>" + o["remark"] + "</td>";
            body += "<td>" + o["createName"] + "</td>";
            body += "<td>" + o["createTime"] + "</td>";
            body += "<td>" + o["updateName"] + "</td>";
            body += "<td>" + o["updateTime"] + "</td>";
            body += "</tr>";
        })
        tableToXlsx(head, '产品类型', body)
        console.log(table)
    }
}

function tableToXlsx(head: any, filename: any, body: any) {
    const uri = 'data:application/vnd.ms-excel;base64,',
        template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`;

    const a = document.createElement('a');
    a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
    a.download = filename;
    a.click();
    document.removeChild(a);
}
//模板下载
const downloadHandler = () => {
    window.open(baseURL + 'excel')
}
//导入
const importHandler = () => {

    const inputEle: HTMLInputElement = document.createElement('input')
    inputEle.type = 'file'
    inputEle.id = 'fileUploadExcel'
    inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
    inputEle.addEventListener('change', (e) => {
        const formData = new FormData()
        if (inputEle.files !== null) {
            formData.append('file', inputEle.files[0] || '')
        } else {
            Message.warning('未选择文件！');
            return
        }
        pageData.pageLoading = true
        axios.post(baseURL + '/product/productType/analyseProductTypeModelModel', formData, {
            headers: {
                "Content-Type": 'multipart/form-data',
                "token": sessionStorage.getItem('USER-TOKEN-KEY')
            },
        }).then((result) => {
            if (result.data['code'] === 200) {
                Message.success('导入成功')
            } else {
                Message.error(result.data.message)
            }

        }).finally(() => {
            pageData.pageLoading = false
            doRefresh()
        })
    })
    inputEle.click()
}

let dataListXl = ref<any[]>([])

const focusSelsss = (val: any) => {
    post({
        url: 'purchase/MaterialSubClass/getList',
        data: {
            bigClassName: val
        }
    }).then((res: any) => {
        if (res.code == 200) {
            dataListXl.value = res.data
        } else {
            Message.error('获取物料小类失败')
        }
    })
}

//下拉框得到焦点
const focusSels = () => {
    selCxAlls({ bigClassName: '' })
}
//下拉数据 
const optionss = ref<any>(pageData.nameLists);
const loadings = ref(false);
const handleSearchs = (value: any) => {
    if (value) {
        const ob = { bigClassName: value }
        loadings.value = true;
        window.setTimeout(() => {
            selCxAlls(ob);
            optionss.value = pageData.nameLists;
            loadings.value = false;
        }, 200)
    } else {
        optionss.value = []
    }
};
//下拉框查询
function selCxAlls(val: any) {
    post({
        url: "purchase/MaterialBigClass/getFieldValue",
        data: val
    }).then(({ data, code }: any) => {
        if (code === 200) {
            console.log(data);
            // (data as string[]).splice(0, 0, "全部");
            pageData.nameLists = data;

        } else {
            Message.error({
                content: "查询失败！",
                duration: 5000,
            });
        }
    });
}

//下拉框得到焦点
const focusSels1 = () => {
    selCxAlls1({ subClassName: '' })
}
//下拉数据 
const optionss1 = ref<any>(pageData.nameLists1);
const loadings1 = ref(false);
const handleSearchs1 = (value: any) => {
    if (value) {
        const ob = { subClassName: value }
        loading.value = true;
        window.setTimeout(() => {
            selCxAlls1(ob);
            optionss1.value = pageData.nameLists1;
            loadings1.value = false;
        }, 200)
    } else {
        optionss1.value = []
    }
};
//下拉框查询
function selCxAlls1(val: any) {
    post({
        url: "purchase/MaterialSubClass/getFieldValue",
        data: val
    }).then(({ data, code }: any) => {
        if (code === 200) {
            console.log(data);
            // (data as string[]).splice(0, 0, "全部");
            pageData.nameLists1 = data;

        } else {
            Message.error({
                content: "查询失败！",
                duration: 5000,
            });
        }
    });
}
const headerShow = ref<boolean>(true)
   //设置权限
        // ['查询', '新增', '删除', '导出', '导入']
        const permissionStore = usePermission()

        if (permissionStore.hasPermisson('wlzl-wlgg.cx')) {

            pageData.btnList.push("查询")
        }
        if (permissionStore.hasPermisson('wlzl-wlgg.xz')) {
            pageData.btnList.push("新增")
        }
        if (permissionStore.hasPermisson('wlzl-wlgg.sc')) {
            pageData.btnList.push("删除")
        }
        // if (permissionStore.hasPermisson('jslx.dc')) {
        //     pageData.btnList.push("导出")
        // }
        // if (permissionStore.hasPermisson('jslx.dr')) {
        //     pageData.btnList.push("导入")
        // }
        if (permissionStore.hasPermisson('wlzl-wlgg.xg')) {
            pageData.isEdit = true
        }
</script>

<style lang="less">

</style>